// pages/cart/index.js
import {
  showModal,
  showToast
} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function (options) {
    const address = wx.getStorageSync("address") || {}
    this.setData({
      address
    });
    // 1 获取缓存中的购物车数据
    const cart = wx.getStorageSync("cart") || [];
    this.setCart(cart)

  },
  handleChooseAddress() {
    wx.chooseAddress({
      success: (res) => {
        console.log(res);
        let address = res
        address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
        // 5 存入到缓存中
        wx.setStorageSync("address", address);
      }
    })
  },
  //全选
  handleItemAllCheck() {
    let {
      allChecked,
      cart
    } = this.data
    allChecked = !allChecked
    cart.forEach(e => e.checked = allChecked)
    this.setCart(cart)
  },
  // 点击选中
  handeItemChange(e) {
    let {
      cart
    } = this.data
    const index = e.currentTarget.dataset.index
    cart[index].checked = !cart[index].checked
    this.setCart(cart)
  },
  setCart(cart) {
    let allChecked = true;
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(e => {
      if (e.checked) {
        totalNum += e.num
        totalPrice += e.num*e.goods_price
      } else {
        allChecked = false
      }
    })
    // 判断数组是否为空
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      cart,
      allChecked,
      totalNum,
      totalPrice
    });
    wx.setStorageSync("cart", cart);
  },
  async handleItemNumEdit(e) {
    const {
      operation,
      index
    } = e.currentTarget.dataset;
    let {
      cart
    } = this.data;

    if (operation == -1) {
      if (cart[index].num === 1) {
        const res = await showModal({
          content: "您是否要删除？"
        })
        if (res.confirm) {
          cart.splice(index,1)
        }
      }else{
        cart[index].num += operation;
      }
    }
    if (operation == 1) {
      cart[index].num += operation;
    }
    this.setCart(cart)
  },
 async handlePay(){
        // 1 判断收货地址
        const {address,totalNum}=this.data;
        if(!address.userName){
          await showToast({title:"您还没有选择收货地址"});
          return
        }
        if(totalNum===0){
          await showToast({title:"您还没有选购商品"});
          return
        }
            // 3 跳转到 支付页面
    wx.navigateTo({
      url: '/pages/pay/index'
    });
      
  }
  
})